package pdfwater;

import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class WaterMark {
	// 添加水印图片路径
	private static final String imageFilePath = "image/boclogo.jpg";

	public static void waterMark(String inputFile, String outputFile, String waterMarkName) {
		try {
			PdfReader reader = new PdfReader(inputFile);
			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
			// 设置密码
			/*stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), permission,
			        false);*/
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
			        BaseFont.NOT_EMBEDDED);
			int total = reader.getNumberOfPages() + 1;
			Image image = Image.getInstance(imageFilePath);
			image.setAbsolutePosition(250, 100);
			PdfContentByte under;
			int j = waterMarkName.length();
			char c = 0;
			int rise = 0;
			for (int i = 1; i < total; i++) {
				rise = 500;
				under = stamper.getUnderContent(i);
				// 添加图片水印
				under.addImage(image);
				under.beginText();
				under.setColorFill(BaseColor.CYAN);
				under.setFontAndSize(base, 30);
				// 设置水印文字字体倾斜 开始
				if (j >= 15) {
					under.setTextMatrix(100, 100);
					for (int k = 0; k < j; k++) {
						under.setTextRise(rise);
						c = waterMarkName.charAt(k);
						under.showText(c + "");
						rise -= 25;
					}
				} else {
					under.setTextMatrix(100, 100);
					for (int k = 0; k < j; k++) {
						under.setTextRise(rise);
						c = waterMarkName.charAt(k);
						under.showText(c + "");
						rise -= 18;
					}
				}
				// 字体设置结束
				under.endText();
				// 画一个圆
				// under.ellipse(250, 450, 350, 550);
				// under.setLineWidth(1f);
				// under.stroke();
			}
			stamper.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		waterMark("pdffolder/Helloworld.pdf", "pdffolder/Helloworld_watermark.pdf",
		        "这是水印这是水印这是水印这是水印这是水印这是水印这是水印这是水印");
	}

}
